<?php
class BeneficiaryDetailsPage extends MemberPage {
    private static $default_parent = 'MyAdminPage';

    private static $db = array();

    private static $has_one = array();

}

class BeneficiaryDetailsPage_Controller extends MemberPage_Controller {

    /**
     * An array of actions that can be accessed via a request. Each array element
     * should be an action name, and the
     * permissions or conditions required to allow the user to access it.
     *
     * <code>
     * array (
     *     'action', // anyone can access this action
     *     'action' => true, // same as above
     *     'action' => 'ADMIN', // you must have ADMIN permissions to access this
     * action
     *     'action' => '->checkAction' // you can only access this action if
     * $this->checkAction() returns true
     * );
     * </code>
     *
     * @var array
     */
    private static $allowed_actions = array('Form');

    public function init() {
        parent::init();
    }
    
    function Form() {
        $fields = singleton('Beneficiary')->getBeneficiaryFormFields();
        $actions = FieldList::create(
            ResetFormAction::create("doReset", _t('BeneficiaryDetailsPage.BUTTONRESET', 'Reset')),
            FormAction::create("doSave", _t('BeneficiaryDetailsPage.BUTTONUPDATE', 'Update'))
        );
        $validator = RequiredFields::create('Name', 'Relationship', 'Passport', 'Contact');
        $beneficiary = Beneficiary::get()->find('MemberID', $this->CurrentMember()->ID);
        return Form::create($this, 'Form', $fields, $actions, $validator)->loadDataFrom($beneficiary ? $beneficiary : array());
    }
    
    function doSave($data, $form) {
        try {
            $beneficiary = Beneficiary::get()->find('MemberID', $this->CurrentMember()->ID);
            if(!$beneficiary){
                $beneficiary = Beneficiary::create()->setField('MemberID', $this->CurrentMember()->ID);
                $beneficiary->write();
            }
            $form->saveInto($beneficiary);
            $beneficiary->write();
            $form->sessionMessage(_t('BeneficiaryDetailsPage.SUCCESS_UPDATE_BENEFICIARY_DETAILS', 'Beneficiary details have been updated successfully'), 'success');
        }
        catch(ValidationException $e) {
            $form->sessionMessage($e->getResult()->message(), 'error');
        }
        return $this->redirectBack();
    }
}
